#coding:utf-8;
"""
Author: 封加清
"""
__author__ = '封加清'
__license__ = 'fastapi'
__version__ = 'v0.66.0'

import json
import requests
import os
import uvicorn
from fastapi import FastAPI, Form
from uvicorn.config import Config
from uvicorn.server import logger               # 导入uvicorn自带logger 日志输出
from pydantic import BaseModel
from starlette.requests import Request
from starlette.responses import FileResponse
from starlette.templating import Jinja2Templates


# 是否运行在正式环境
PROG = os.path.basename(__file__)               # 脚本文件名
IN_PROD = (PROG == 'webhook.py')                # if webhook.py   bool
# IN_PROD==False ROBOT_URL=='https:..<k1>'  反之 https...<k2>
ROBOT_URL = IN_PROD and 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=<k2>' or 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=<k1>'
PORT = IN_PROD and 10000 or 9090                # IN_PROD==False  port 9090 反之 10000

######### WEBAPP ROUTERS ###############
app = FastAPI()     # fastapi实例化

# 创建一个templates（模板）对象，以后可以重用。
templates = Jinja2Templates(directory="templates")

# Request在路径操作中声明一个参数，该参数将返回模板。
# 使用templates创建渲染并返回TemplateResponse，
@app.get('/')
async def hello(request: Request):
    return templates.TemplateResponse("hello.html", {'request': request})

# 文件获取  http://127.0.0.1:9090/assets/E:/code/appfile.exe
@app.get('/assets/{file_name:path}')
async def server_static(file_name: str):
    return FileResponse(path=file_name, filename=file_name)

######### WEBAPP ROUTERS WRITE YOUR CODE BELOW###############
@app.post('/start/')
async def run_start(comm: str = Form(...)):   # 接收表单字段
    return {"response":'200', "text": comm}    # 返回代码200, 和请求数据

######### BUILT-IN ROUTERS ###############
@app.head('/__exit')  # 请求无返回信息
@app.get('/__exit')   # 两请求
async def __exit():
    global server               # 全局使用
    server.should_exit = True   # server 退出 程序停止运行

######### Robot Message ################
def send_message_to_robot(msg):
    if msg:  # 消息不为空, 请求企业微信接口, 推送消息
      r = requests.post(ROBOT_URL, (bytes(json.dumps({'msgtype': 'text', 'text': {'content': msg}}), 'utf-8')))
      print(r.status_code, r.reason)  # 输出请求状态码,返回信息
      print(r.text)

# 发送消息数据模型
class Item(BaseModel):
    object_kind: str = None
    commits: list = [None]
    user_name: str = None
    repository: dict = {None}

@app.post('/webhook/')
async def webhook(json_data: Item):                 # async 异步
    msg = ''
    if json_data.object_kind == 'merge_request':     # 不操作
      pass
    elif json_data.object_kind == 'push':              # 发送消息
      comments_message = "\n".join([item['message']+"\n( "+item['url']+" )\n" for item in json_data.commits])   # 获取消息内容, 消息类型为列表嵌套字典
      msg_tpl = """# %s 提交（%s）\r\nWHAT'S NEW:\r\n```\r\n%s\r\n```"""
      msg = msg_tpl % (json_data.user_name, json_data.repository['name'], comments_message)   # 消息格式化处理
    print("发送的消息: ", msg)
    send_message_to_robot(msg)
    return {"response": msg}


if __name__=='__main__':
    try:
        config = Config(app, **{"host": '0.0.0.0', "port": PORT})    # uvicorn 参数
        server = uvicorn.Server(config=config)                  # 获取uvicorn.Server
        server.run()                                            # 运行服务
    except Exception as ex:                                     # 异常
        errs = "Exception: %s" % repr(ex)
        logger.error(errs)                                      # 异常日志方式输出